# ... existing code ...

class Authentication:

    def perform_security_access(self, security_level, key, algorithm=0x01, timeout=5):
        """
        执行UDS安全访问认证流程
        :param security_level: 安全等级 (0x01-0x7F)
        :param key: 共享密钥 (16字节)
        :param algorithm: 安全算法字段 (默认0x01)
        :param timeout: 超时时间(秒)
        :return: (认证是否成功, 总耗时, 认证结果消息)
        """
        try:
            start_time = time.time()
            
            # 步骤1: 发送种子请求
            seed_request = [0x27, security_level]
            recv_data, _ = self.req_and_res_can(seed_request[0], seed_request[1:], enblePrint=False)
            
            # 检查响应是否为67 XX1 XX...XX2格式
            if len(recv_data) < 3 or recv_data[0] != 0x67 or recv_data[1] != security_level:
                return False, time.time()-start_time, recv_data
            
            # 提取种子值 (从第3字节开始)
            seed = recv_data[2:]
            
            # 步骤4: 计算Token (AES-CMAC)
            # 注意: 这里需要实现AES-CMAC算法或调用相关库
            token = self._calculate_aes_cmac(key, seed)
            
            # 步骤5: 发送Token
            token_request = [0x27, algorithm] + token
            recv_data, _ = self.req_and_res_can(token_request[0], token_request[1:], enblePrint=False)
            
            # 检查最终响应是否为67 XX3
            success = (len(recv_data) >= 2 and 
                      recv_data[0] == 0x67 and 
                      recv_data[1] == algorithm)
            
            total_time = time.time() - start_time
            return success, total_time, recv_data
            
        except Exception as e:
            logging.error(f"Security access failed: {str(e)}")
            return False, time.time()-start_time, []

    def _calculate_aes_cmac(self, key, seed):
        """
        计算AES-CMAC值 (需要实现或调用加密库)
        :param key: 16字节密钥
        :param seed: 种子数据
        :return: 8字节Token
        """
        # 这里需要实现AES-CMAC算法或调用加密库
        # 示例: 使用pycryptodome库
        try:
            from Crypto.Hash import CMAC
            from Crypto.Cipher import AES
            
            cobj = CMAC.new(key, ciphermod=AES)
            cobj.update(bytes(seed))
            return list(cobj.digest()[:8])  # 返回前8字节作为Token
            
        except ImportError:
            logging.error("pycryptodome library not installed")
            return [0] * 8  # 返回默认值
            
        except Exception as e:
            logging.error(f"AES-CMAC calculation error: {str(e)}")
            return [0] * 8  # 返回默认值


success, time_used, result = uds.perform_security_access(
    security_level=0x01,
    key=[0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF,
         0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10]
)

if success:
    print(f"认证成功, 耗时: {time_used:.2f}秒")
else:
    print(f"认证失败, 响应: {result}")